<script setup>
  import { ref } from 'vue'
  import ChannelSelect from './ChannelSelect.vue'
  import { Plus } from '@element-plus/icons-vue'
  // 引入富文本编辑器
  import { QuillEditor } from '@vueup/vue-quill'
  import '@vueup/vue-quill/dist/vue-quill.snow.css'

  // 引入发布文章的方法
  import { editArticleService, publishArticleService, getArticleDetailService } from '@/api/article'
  import { baseURL } from '@/utils/request'
  // 引入图片转换方法
  import { imageUrlToFile } from '@/utils/image'

  const visibleDrawer = ref(false)
  const defaultForm = {
    title: '',
    cate_id: '',
    cover_img: '',
    content: '',
    state: ''
  }

  const formModel = ref({ ...defaultForm })
  // 表单校验规则
  const rules = {
    title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
    cate_id: [{ required: true, message: '请选择文章分类', trigger: 'blur' }],
    cover_img: [{ required: true, message: '请上传文章封面', trigger: 'blur' }],
    content: [
      {
        required: true,
        message: '请输入文章内容',
        // trigger: ['blur', 'input'],
        validator: (rule, value, callback) => {
          // 移除HTML标签并检查实际文本内容
          const textContent = value.replace(/<[^>]+>/g, '').trim()
          if (!textContent) {
            callback(new Error('请输入文章内容'))
          } else {
            callback()
          }
        }
      }
    ]
  }

  // 图片上传相关(预览)
  const imgUrl = ref('')
  const onUploadFile = (uploadFile) => {
    imgUrl.value = URL.createObjectURL(uploadFile.raw)
    formModel.value.cover_img = uploadFile.raw
  }

  // 发布文章
  // 引入表单校验
  const formRef = ref()
  // 富文本编辑器失去焦点手动校验
  const handleBlur = () => {
    formRef.value.validateField('content')
  }

  const emit = defineEmits(['success'])
  const handlePublish = async (state) => {
    formModel.value.state = state
    // 当前接口需要的是formData对象
    // 将普通对象转换为formData对象
    const formData = new FormData()
    for (let key in formModel.value) {
      formData.append(key, formModel.value[key])
    }
    // 校验表单
    await formRef.value.validate()

    if (formModel.value.id) {
      // 编辑
      await editArticleService(formData)
      ElMessage.success('修改成功')
      // 关闭抽屉
      visibleDrawer.value = false
      // 刷新文章列表
      emit('success', 'edit')
    } else {
      // 发布
      await publishArticleService(formData)
      ElMessage.success('发布成功')
      // 关闭抽屉
      visibleDrawer.value = false
      // 刷新文章列表
      emit('success', 'add')
    }
  }

  const quillEditorRef = ref()
  const open = async (row) => {
    visibleDrawer.value = true
    if (row.id) {
      // 基于row.id发送请求,获取编辑对应的详情数据,进行回显
      const res = await getArticleDetailService(row.id)
      formModel.value = {
        ...res.data.data
      }
      // 图片需要单独处理
      imgUrl.value = baseURL + formModel.value.cover_img
      // 提交给后台需要的格式是file对象(后端的锅)
      // 需要将网络图片地址转换成file对象,存储起来将来便于提交
      const file = await imageUrlToFile(imgUrl.value, formModel.value.cover_img)
      formModel.value.cover_img = file
    } else {
      // 发布文章则重置表单
      formModel.value = {
        ...defaultForm
      }
      // 图片和富文本编辑器要手动重置
      imgUrl.value = ''
      quillEditorRef.value.setHTML('')
    }
  }
  // 向外暴露方法
  defineExpose({
    open
  })
</script>
<template>
  <!-- 抽屉 -->
  <el-drawer
    v-model="visibleDrawer"
    :title="formModel.id ? '编辑文章' : '添加文章'"
    direction="rtl"
    size="50%"
  >
    <!-- 发表文章表单 -->
    <el-form :model="formModel" :rules="rules" ref="formRef" label-width="100px">
      <el-form-item label="文章标题" prop="title">
        <el-input v-model="formModel.title" placeholder="请输入标题"></el-input>
      </el-form-item>
      <el-form-item label="文章分类" prop="cate_id">
        <channel-select v-model="formModel.cate_id" style="width: 100%"></channel-select>
      </el-form-item>
      <el-form-item label="文章封面" prop="cover_img">
        <!-- 此处需要关闭自动上传,不需要配置action等参数
             只需要做前端的本地预览图片即可,无需在提交前上传图片
             语法:
             1. 定义一个变量,用于存储图片的url
             2. 定义一个方法,用于处理图片上传
             3. 方法中,使用URL.createObjectURL()方法,将图片转换为url
             4. 赋值给变量
        -->
        <el-upload
          class="avatar-uploader"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="onUploadFile"
        >
          <img v-if="imgUrl" :src="imgUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="文章内容" prop="content">
        <div class="editor">
          <quill-editor
            ref="quillEditorRef"
            theme="snow"
            v-model:content="formModel.content"
            content-type="html"
            @blur="handleBlur"
          />
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handlePublish('已发布')">发布</el-button>
        <el-button type="info" @click="handlePublish('草稿')">草稿</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>
<style lang="scss" scoped>
  .avatar-uploader {
    :deep() {
      .avatar {
        width: 178px;
        height: 178px;
        display: block;
      }
      .el-upload {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
      }
      .el-upload:hover {
        border-color: var(--el-color-primary);
      }
      .el-icon.avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        text-align: center;
      }
    }
  }
  .editor {
    width: 100%;
    :deep(.ql-editor) {
      min-height: 200px;
    }
  }
</style>
